/**
 *
 */
// import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";
import { createRouter, createWebHashHistory } from "vue-router";
import { getRole } from "../api";
import { mainStore } from "../store";
import { getToken } from "../utils/auth"
const routes = [
  {
    path: "/",
    redirect: "/login", //重定向
  },
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/login.vue"),

  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/home/home.vue"),

  },

];

const router = new createRouter({
  history: createWebHashHistory(),
  routes,
});
//路由拦截
router.beforeEach(async (to, from, next) => {
  console.log('触发路由请求', "to",to)
  console.log('触发路由请求', "from",from)
  // if (to.path === from.path) {
  //   // 如果to和from路径相同，强制刷新页面
  //   // 使用location.reload()来刷新页面

  // } 
  if (to.path === "/login") {

    mainStore().$reset()
    next();
  } else {
    let navData = await getNavData()
    console.log('navData',navData)
    router.addRoute(navData)

    let token = getToken("token");
    // console.log(token)
    if (token === null || token === "") {
      next("/login");
    } else {
      // console.log(token)
      next();
    }
  }

  // location.reload();
  // next();
});

async function getNavData() {
  var navData_res = mainStore().getNav()
  var navData
  console.log("navData_res",navData_res);
  if (
    navData_res.length === 0
  ) {
    let res = await getRole();
    console.log('路由中getRole',res.data);

    mainStore().setNav(res.data)

    navData = transData(res.data)
    console.log('navData',navData)
  } else {
    navData = transData(navData_res)
  }
  console.log('navData1',navData)
  return navData

  // console.log('navData',navData)
}
function transData(res) {
  let homeRoutes = routes.filter(v => v.path === "/home")[0]
  homeRoutes.children = []
  console.log("res",res)
  Object.keys(res).forEach(item => {

    console.log("item",item)
    
    // console.log('循环item',res[item])
    if (Array.isArray(res[item]["children"])) {
      console.log('循环item',res[item]["children"])
      // console.log('循环item0',res[item]["children"][[Target]][0])
      console.log('循环item.path',res[item]["children"][0].path)
     
     
      res[item]["children"].forEach(item1 => {
        homeRoutes.children.push({
          path: item1.path,
          // name: item1.path,
          component: () => import(`../views/table/${item1.component}/${item1.component}.vue`),
          meta: {
            getpath: item1.getpath,
            addpath: item1.addpath,
            editpath: item1.updatepath,
            deletepath: item1.deletepath

          }
        })
      })
    }else{
      console.error(`Expected 'children' of ${item} to be an array, but got`, res[item]["children"]);
    }



  });
  return homeRoutes
}

export default router;
